package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRespository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.domain.utils.Constants;
import cn.itcast.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private FixedAreaRepository fixedAreaRepository;

	@Autowired
	private OrderRepository orderRepository;

	@Autowired
	private AreaRepository areaRepository;

	@Autowired
	private WorkBillRespository workBillRespository;

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Override
	public void saveOrder(Order order) {

		// 寄件人省市区
		Area sendArea = order.getSendArea();
		// 需要查询区域中的 寄件人的省市区,传入省,市,区
		Area persitArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(), sendArea.getCity(), sendArea.getDistrict());

		// 收件人省市区
		Area recArea = order.getRecArea();
		Area persitRecArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(), sendArea.getCity(), sendArea.getDistrict());

		// 手动设置订单的一些属性
		order.setSendArea(persitArea);
		order.setRecArea(persitRecArea);

		order.setOrderNum(UUID.randomUUID().toString());
		order.setOrderTime(new Date());
		order.setStatus("1");// 待取件

		// 自动分单逻辑,基于crm地址完全匹配,获取定区,匹配快递员
		String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/crm_management/services/customerService/customer/findFixedAreaIdByAddress?address=" + order.getSendAddress()).accept(MediaType.APPLICATION_JSON).get(String.class);
		System.err.println("fixedAreaId"+fixedAreaId);
		// 判断fixedAreaId是否为空
		if (fixedAreaId != null) {
			// 得到定区
			FixedArea oneFixedArea = fixedAreaRepository.findOne(fixedAreaId);
			// 找到快递员
			Iterator<Courier> iterator = oneFixedArea.getCouriers().iterator();
			// 找到的定区内不一定有快递员, 所以需要判断
			if (iterator.hasNext()) {
				Courier courier = iterator.next();
				if (courier != null) {
					// 自动分单成功
					System.out.println("根据地址完全匹配,自动分单成功......");
					// 保存订单
					saveOrder(order, courier);

					// 生成工单. 发送短信
					generateWorkBill(order);

					return;
				}
			}
		}
		// 自动分单业务, 通过省市区,查询分区关键字,匹配地址,基于分区实现自动分单
		for (SubArea subArea : persitArea.getSubareas()) {
			// 当前客户下单是否包含分区关键字
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				// 找到分区, 然后找到定区, 然后找到快递员
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				// 找到的定区内不一定有快递员, 所以需要判断
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						// 自动分单成功
						System.out.println("通过分区找到的关键字分单成功.....");
						// 保存订单
						saveOrder(order, courier);

						// 生成工单. 发送短信
						generateWorkBill(order);

						return;
					}
				}
			}
		}

		// 如果上面的两种方式都没有找到地址,没有分单成功, 就进入人工分单
		// 将状态设置为2
		order.setOrderType("2");
		// 保存
		orderRepository.save(order);
	}

	private void generateWorkBill(final Order order) {
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		final String smsNum = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNum);
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		// 保存
		workBillRespository.save(workBill);

		// 发送短信,调用MQ,
		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg", "短信序号:" + smsNum + ",取件地址是:" + order.getSendAddress() + ",联系人:" + order.getSendName() + ",手机," + order.getTelephone() + ",客户捎了一句话" + order.getSendMobileMsg());
				return mapMessage;
			}
		});
		// 修改工单的状态
		workBill.setPickstate("已通知");
	}

	// 自动分单保存
	private void saveOrder(Order order, Courier courier) {
		// 将快递员关联到订单上
		order.setCourier(courier);
		// 设置单子状态时自动分单的,1 代表是自动分单的
		order.setOrderType("1");

		// 包存订单
		orderRepository.save(order);
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}

}
